<?php

namespace app\index\controller;

use think\Controller;
use think\Db;


class Pay extends Controller
{
    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 支付
     * param  [type] $openid       [用户open_id]
     * param  [type] $order_id     [订单号]
     * param  [type] $amount       [支付金额]
     * param  [type] $call_back    [回调地址]
     */
    public function pay($openid,$order_id,$amount,$call_back='',$note='上车付款')
    {
        // 统一下单
        header('Content-Type:text/html;charset=UTF-8');

        // 导入微信支付sdk
        Vendor('Weixinpay.WxPayConfig');
        Vendor('Weixinpay.WxPayApi');
        Vendor('Weixinpay.JsApiPay');
        Vendor('Weixinpay.WxPayResults');

        $tools=new  \JsApiPay();

        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($note);
        $input->SetAttach("test");
        $input->SetOut_trade_no($order_id);
        $input->SetTotal_fee($amount*100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("test");
        $input->SetNotify_url($call_back);
        $input->SetTrade_type("JSAPI");

        $input->SetOpenid($openid);
        $order = \WxPayApi::unifiedOrder($input);

        $jsApiParameters = $tools->GetJsApiParameters($order);

        if($jsApiParameters){
            $aa = json_decode($jsApiParameters);
            $tt['appId']        = $aa->appId;
            $tt['nonceStr']     = $aa->nonceStr;
            $tt['package']      = $aa->package;
            $tt['signType']     = $aa->signType;
            $tt['timeStamp']    = $aa->timeStamp;
            $tt['paySign']      = $aa->paySign;
        }

        return json($tt);

    }

    /**
     * 微信支付回调
     */
    public function WxReturnOrders()
    {
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];

        // 记录微信回调数据
         file_put_contents('1.txt',$xml);
         
        libxml_disable_entity_loader(true);
        $arr= json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        if($arr['return_code'] == 'SUCCESS'){

            // 业务逻辑处理
            //修改订单状态
            $order_status=Db::name('dd_publish_orders')->where('id',input('id'))->update(['status'=>1]);

            if ($order_status){

                echo 'success';

            }else{

                //echo 'error';
            }
        }
    }


}
